<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller\users;

use app\admin\controller\Auth;
use app\common\model\users\Log as UsersLog;
use app\common\model\users\WithdrawLog as UsersWithdrawLog;
use app\common\model\users\Recharge;
use mall\response\Response;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use app\common\model\users\WalletDetail;
use app\common\model\users\Wallet;

class Finance extends Auth {

    private $type = ["1"=>"银行卡","2"=>"支付宝","3"=>"微信"];
    private $status = ["0"=>"审核中","1"=>"已提现","2"=>"未通过"];

    public function index(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $condition = ["log.action"=>4];

            $usersLog = new UsersLog();
            $list = $usersLog->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }

            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch();
    }

    public function fund(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $condition = ["log.action"=>0];

            $usersLog = new UsersLog();
            $list = $usersLog->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }

            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch();
    }

    public function refund(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $condition = ["log.action"=>3];

            $usersLog = new UsersLog();
            $list = $usersLog->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }

            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch();
    }

    public function point(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $condition = ["log.action"=>1];

            $usersLog = new UsersLog();
            $list = $usersLog->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }

            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch();
    }

    public function exp(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $condition = ["log.action"=>2];

            $usersLog = new UsersLog();
            $list = $usersLog->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }

            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch();
    }

    public function withdrawLogList(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $params = Request::param("key/a",[],"trim,strip_tags");
            $condition = [];
            if(!empty($params['create_time'])){
                [$start_time,$end_time]=explode('~',$params['create_time']);
                $condition[]=['withdraw_log.create_time','>=',strtotime($start_time)];
                $condition[]=['withdraw_log.create_time','<=',strtotime($end_time)];
            }
            if(!empty($params['channel'])){
                $condition[]=['channel','=',$params['channel']];
            }
            if(!empty($params['username'])){
                $condition[]=['users.username','like',"%{$params['username']}%"];
            }
            $usersWithdrawLog = new UsersWithdrawLog();
            $list = $usersWithdrawLog->get_list($condition,$limit);
            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }
            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch('',[
            'channel_list'=>UsersWithdrawLog::getChannelList(),
        ]);
    }

    public function rechargeLogList(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $params = Request::param("key/a",[],"trim,strip_tags");
            $condition = [];
            if(!empty($params['create_time'])){
                [$start_time,$end_time]=explode('~',$params['create_time']);
                $condition[]=['recharge.create_time','>=',strtotime($start_time)];
                $condition[]=['recharge.create_time','<=',strtotime($end_time)];
            }
            if(!empty($params['channel'])){
                $condition[]=['channel','=',$params['channel']];
            }
            if(!empty($params['username'])){
                $condition[]=['users.username','like',"%{$params['username']}%"];
            }
            if(isset($params['status']) && $params['status']!=-1){
                $condition[]=['recharge.status','=',$params['status']];
            }
            $recharge = new Recharge();
            $list = $recharge->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }
            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }
        return View::fetch('',[
            'channel_list'=>Recharge::getChannelList(),
            'status_list'=>Recharge::getStatuslList(),
        ]);
    }

    public function walletDetail(){
        if(Request::isAjax()){
            $limit = Request::get("limit");
            $params = Request::param("key/a",[],"trim,strip_tags");
            $condition = [];
            if(!empty($params['create_time'])){
                [$start_time,$end_time]=explode('~',$params['create_time']);
                $condition[]=['wallet_detail.create_time','>=',strtotime($start_time)];
                $condition[]=['wallet_detail.create_time','<=',strtotime($end_time)];
            }
            if(!empty($params['username'])){
                $condition[]=['users.username','like',"%{$params['username']}%"];
            }
            if(!empty($params['type'])){
                $condition[]=['wallet_detail.type','=',$params['type']];
            }
            $walletDetail = new WalletDetail();
            $list = $walletDetail->getList($condition,$limit);

            if(empty($list['data'])){
                return Response::returnArray("当前还没有数据哦！",1);
            }
            return Response::returnArray("ok",0,$list['data'],$list['count']);
        }

        return View::fetch('',[
            'type_list'=>WalletDetail::getTypeList(),
        ]);
    }

    public function handle(){
        $id = Request::param("id");
        if(($row = Db::name("users_withdraw_log")->where(["id"=>$id])->find()) == false){
            if(Request::isAjax()) {
                return Response::returnArray("您要查找的内容不存在！", 0);
            }else{
                $this->error("您要查找的内容不存在！");
            }

        }
        $str = '&nbsp;&nbsp;';
        if($row["type"] == 1){
            $str .= "<span>卡号：" . $row["code"] . '</span>&nbsp;&nbsp;';
            $str .= "<span>开户地址：" . $row["address"] . '</span>&nbsp;&nbsp;';
            $str .= "<span>银行：" . $row["bank_name"] . '</span>&nbsp;&nbsp;';
        }else if($row["type"] == 2){
            $str .= "<span>用户名：" . $row["username"] . '</span>&nbsp;&nbsp;';
            $str .= "<span>支付宝：" . $row["account"] . '</span>&nbsp;&nbsp;';
        }else if($row["type"] == 3){
            $str .= "<span>用户名：" . $row["username"] . '</span>&nbsp;&nbsp;';
            $str .= "<span>微信：" . $row["account"] . '</span>&nbsp;&nbsp;';
        }
        $row["string"] = $str;
        if(($user = Db::name("users")->where(["id"=>$row["user_id"]])->find()) == false){
            if(Request::isAjax()) {
                return Response::returnArray("您操作的会员不存在！", 0);
            }else{
                $this->error("您操作的会员不存在！");
            }
        }
        if(Request::isAjax()){
            $data = Request::post();

            $u = Db::name("users")->where(["id"=>$row["user_id"]])->find();
            if($u["amount"] < $row["price"]){
                return Response::returnArray("操作失败，余额不足！",0);
            }

            Db::startTrans();
            try {
                Db::name("users_withdraw_log")->where(["id"=>$id])->update([
                    "msg"=>$data["msg"],
                    "status"=>$data["status"],
                    "update_time"=>time()
                ]);

                if($data["status"] == 1){
                    Db::name("users")
                        ->where(["id"=>$row["user_id"]])
                        ->dec("amount",$row["price"])->update();
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return Response::returnArray("操作失败，请稍后在试！",0);
            }

            return Response::returnArray("操作成功！");
        }

        return View::fetch("",[
            "id"=>$id,"user"=>$user,"row"=>$row
        ]);
    }


    //提现审核
    public function review(){
        if(Request::isAjax()){
            $id = Request::param('id',0,'intval');
            $status = Request::param('status',0,'intval');
            if(!$id){
                return Response::returnArray("非法操作",1);
            }
            if(!UsersWithdrawLog::isValidStatus($status)){
                return Response::returnArray("无效参数",1);
            }
            $withdraw_log=UsersWithdrawLog::find($id);
            if(!$withdraw_log){
                return Response::returnArray("记录不存在！",1);
            }
            if($withdraw_log['status']!=UsersWithdrawLog::STATUS_WAIT){
                return Response::returnArray("无效操作！",1);
            }
            //钱包
            $wallet = (new Wallet())->findOne($withdraw_log['user_id'])->toArray();
            Db::startTrans();
            try {
                //成功
                if($status==UsersWithdrawLog::STATUS_SUCCESS){
                    (new Wallet())->updateFromWalletDetaisl($withdraw_log['user_id'],$wallet['ver'],$withdraw_log['amount'],0);
                    $wallet = (new Wallet())->findOne($withdraw_log['user_id'])->toArray();
                    (new WalletDetail())->recordAddToWallet($wallet,bcsub(0,$withdraw_log['amount'],2),'withDraw',['related_id'=>$withdraw_log['id']]);
                }else{
                    (new Wallet())->updateFromWalletDetaisl($withdraw_log['user_id'],$wallet['ver'],$withdraw_log['amount'],0);
                }
                UsersWithdrawLog::where('id',$id)->update(['status'=>$status]);
                // 提交事务
                Db::commit();
                return Response::returnArray("操作成功",0);
            } catch (\Throwable $t) {
                // 回滚事务
                Db::rollback();
                return Response::returnArray($t->getMessage(),$t->getCode());
            }
        }
         return View::fetch("",[
            "status_list"=>UsersWithdrawLog::getValidStatusList(),
        ]);
    }

    //充值审核
    public function audit(){
        if(Request::isAjax()){
            $id = Request::param('id',0,'intval');
            $status = Request::param('status',0,'intval');
            if(!$id){
                return Response::returnArray("非法操作",1);
            }
            if(!Recharge::isValidStatus($status)){
                return Response::returnArray("无效参数",1);
            }
            $recharge=Recharge::find($id);
            if(!$recharge){
                return Response::returnArray("记录不存在！",1);
            }
            if($recharge['status']!=Recharge::STATUS_PENDING  || $recharge['channel']!=Recharge::CAHNNEL_OFFLINE){
                return Response::returnArray("无效操作！",1);
            }
            //钱包
            $wallet = (new Wallet())->findOne($recharge['user_id'])->toArray();
            Db::startTrans();
            try {
                //成功
                if($status==Recharge::CAHNNEL_SUCCESS){
                    (new WalletDetail())->recordAddToWallet($wallet,bcsub($recharge['amount'],0,2),'recharge',['related_id'=>$recharge['id']]);
                }
                Recharge::where('id',$id)->update(['status'=>$status]);
                // 提交事务
                Db::commit();
                return Response::returnArray("操作成功",0);
            } catch (\Throwable $t) {
                // 回滚事务
                Db::rollback();
                return Response::returnArray($t->getMessage(),$t->getCode());
            }
        }
         return View::fetch("",[
            "status_list"=>Recharge::getValidStatusList(),
        ]);
    }
}
